#include "geminai_vision_1106.h"
#include <stdio.h>
#include <string.h>
#include "geminai_frig.h"
#include "geminai_mqtt_cache.h"
#include "geminai_audio.h"

int analyze_vision_event(char* event, void *para)
{
    if(strcmp(event, "opened_door_event") == 0 && strlen(event) == strlen("opened_door_event")){
        app_play_wav(1, "/spiffs/open_door.wav");
        fans_reset_work();
    }
        if(strcmp(event, "closed_door_event") == 0 && strlen(event) == strlen("closed_door_event")){
        fans_set_work();
    }

    return vision_event_report(event, para);
}

void door_event_report(char* event, int angle, int open_count)
{
    cJSON *root = cJSON_CreateObject();
    if(strcmp(event, "opened_door_event") == 0 && strlen(event) == strlen("opened_door_event")){
        cJSON_AddNumberToObject(root, "angle", angle);
        app_play_wav(1, "/spiffs/open_door.wav");
        fans_reset_work();
    }
        if(strcmp(event, "closed_door_event") == 0 && strlen(event) == strlen("closed_door_event")){
        fans_set_work();
    }
    
    time_t now;
    time(&now);
    struct tm *timeinfo = localtime(&now);
    char time_str[20];
    memset(time_str, 0, sizeof(time_str));
    sprintf(time_str, "%lld", now*1000);
    cJSON_AddStringToObject(root, "event_time", time_str);

    char client_sn[128] = {0};
    sprintf(client_sn, "%.04d%.02d%.02d%.02d%.02d%.02d%s%.06d", 
             timeinfo->tm_year + 1900, timeinfo->tm_mon + 1, timeinfo->tm_mday, 
             timeinfo->tm_hour, timeinfo->tm_min, timeinfo->tm_sec, 
             base_station.imei, open_count);

    cJSON_AddStringToObject(root, "client_sn", client_sn);
    cJSON_AddStringToObject(root, "asset_id", base_station.asset_id);
    char *out = cJSON_PrintUnformatted(root);
    printf("door event: %s\n", out);
    cJSON_Delete(root);

    vision_event_report(event, out);
}